package com.adou.d1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Connecttion事务
 */
public class JDBCDemo2 {
    public static void main(String[] args) throws Exception {
        // 1.注册驱动
        Class.forName("com.mysql.jdbc.Driver");

        String url = "jdbc:mysql://127.0.0.1/db1?useSSL=false";
        String username = "root";
        String password = "root";
        // 2.获取连接
        Connection conn = DriverManager.getConnection(url, username, password);

        // 3.sql
        String sql = "update account1 set money = 3000 where id = 1";
        String sql2 = "update account1 set money = 3000 where id = 2";

        // 4.获取执行sql对象
        Statement stmt = conn.createStatement();
        try {
            // 开启事务
            conn.setAutoCommit(false);

            // 5.执行sql
            int result = stmt.executeUpdate(sql);// 受影响行数
            // 6.打印结果
            System.out.println(result);

            int i = 3/0;

            // 5.执行sql
            int result2 = stmt.executeUpdate(sql2);// 受影响行数

            // 6.打印结果
            System.out.println(result2);

            // 提交事务
            conn.commit();
        } catch (SQLException e) {
            // 回滚事务
            conn.rollback();

            // 7.释放资源
            stmt.close();
            conn.close();

            e.printStackTrace();
        }
    }
}
